package cn.edu.qlnu.xky.test.controller;

import cn.edu.qlnu.xky.test.model.Borrow;
import cn.edu.qlnu.xky.test.model.User;
import cn.edu.qlnu.xky.test.service.BookService;
import cn.edu.qlnu.xky.test.service.BorrowService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.tomcat.jakartaee.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : wuweihong
 * @desc : TODO  请填写你的功能描述
 * @date : 2025-06-20
 */


public class BorrowController  extends HttpServlet {

	private static final String ACTION_POSTPONE = "postpone";
	private static final String ACTION_RETURN = "return";
	private static final String ACTION_SEARCH = "search";

	private static final String URL_BOOK_BORROW_SEARCH = "/bookBorrow/search.jsp";

	private static final String MSG_POSTPONE_SUCCESS = "延期成功";
	private static final String MSG_POSTPONE_FAILED = "延期失败";
	private static final String MSG_RETURN_SUCCESS = "归还成功";
	private static final String MSG_RETURN_FAILED = "归还失败";


	public BorrowController() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置字符编码
		request.setCharacterEncoding("UTF-8");

		// 获取当前用户
		User currentUser = getCurrentUser(request);
		if (currentUser == null) {
			// 用户未登录，重定向到登录页或其他处理
			response.sendRedirect(request.getContextPath() + "/login.jsp");
			return;
		}
		// flag为标志，add添加，search为查询
		String action = request.getParameter("flag");
		BorrowService borrowService = new BorrowService();
		System.out.println("flag=" + action);
		String redirectUrl;
		if (action == null) {
			redirectUrl = URL_BOOK_BORROW_SEARCH;
		} else {
			switch (action) {
				case ACTION_POSTPONE:
					String postponeMsg = doPostpone(borrowService, request);
					request.setAttribute("msg", postponeMsg);
					redirectUrl = URL_BOOK_BORROW_SEARCH;
					break;
				case ACTION_RETURN:
					String returnMsg = doReturn(borrowService, new BookService(), request);
					request.setAttribute("msg", returnMsg);
					redirectUrl = URL_BOOK_BORROW_SEARCH;
					break;
				case ACTION_SEARCH:
					doSearch(borrowService, request);
					redirectUrl = URL_BOOK_BORROW_SEARCH;
					break;
				default:
					redirectUrl = URL_BOOK_BORROW_SEARCH;
			}
		}

		forwardToPage(request, response, redirectUrl);
	}



	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}


	private String doPostpone(BorrowService borrowService, HttpServletRequest request) throws IOException {
		String borrowIdStr = request.getParameter("id");
		int borrowId = Integer.parseInt(borrowIdStr);
		Borrow borrowRecord = borrowService.searchById(borrowId);
		if (borrowRecord.getIsExceed()==1) {
			return MSG_POSTPONE_FAILED;
		}
		Date borrowDate = borrowRecord.getBorrowDate();
		Date dueDate = borrowRecord.getDueDate();
		long diffInMillis = Math.abs(dueDate.getTime() - borrowDate.getTime());
		int interval = Math.toIntExact(TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS));
		if (interval > 20) {
			return MSG_POSTPONE_FAILED;
		}else {
			Date newDueDate = new Date(dueDate.getTime() + 1000 * 60 * 60 * 24 * 10);
			borrowRecord.setDueDate(newDueDate);
			boolean updateSuccess = borrowService.updateBorrow(borrowRecord) > 0;
			if (updateSuccess) {
				BookService bookService = new BookService();
				bookService.updateBookCount(borrowRecord.getBookId(), "add");
				return MSG_RETURN_SUCCESS;
			} else {
				return MSG_RETURN_FAILED;
			}
		}
	}

	private String doReturn(BorrowService borrowService, BookService bookService, HttpServletRequest request) {
		String borrowIdStr = request.getParameter("id");
		int borrowId = Integer.parseInt(borrowIdStr);
		Borrow borrowRecord = borrowService.searchById(borrowId);

		if (borrowRecord.getIsReturn() == 1) {
			return MSG_RETURN_SUCCESS;
		}

		borrowRecord.setReturnDate(new Date());
		borrowRecord.setIsReturn(1);

		boolean updateSuccess = borrowService.updateBorrow(borrowRecord) > 0;
		if (updateSuccess) {
			bookService.updateBookCount(borrowRecord.getBookId(), "add");
			return MSG_RETURN_SUCCESS;
		} else {
			return MSG_RETURN_FAILED;
		}
	}

	private void doSearch(BorrowService borrowService, HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		User user = (User) session.getAttribute("curUser");
		String pageNo = request.getParameter("pageNo");
		if (user.getType()==1) {
			String userName = request.getParameter("userName");
			String adminStatus = request.getParameter("adminStatus");
			if (Objects.isNull(userName)) {
				userName = "";
			}
			if (StringUtils.isBlank(adminStatus)) {
				adminStatus = "3";
			}
			request.setAttribute("page", borrowService.searchByStatusAndUserId(userName, Integer.parseInt(adminStatus), null, null ,Integer.parseInt(pageNo)));
		}else {
			Integer userId = user.getId();
			String isReturn = request.getParameter("isReturn");
			Integer isReturnInt = null;
			if (StringUtils.isBlank(isReturn)) {
				isReturnInt = null;
			}else {
				isReturnInt = Integer.parseInt(isReturn);
			}
			request.setAttribute("page", borrowService.searchByStatusAndUserId(null, null, isReturnInt, userId, Integer.parseInt(pageNo)));
		}
	}

	private User getCurrentUser(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		return (session != null) ? (User) session.getAttribute("curUser") : null;
	}

	private void forwardToPage(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {
		request.getRequestDispatcher(url).forward(request, response);
	}


}
